package ping

import (
	"errors"
	probing "github.com/prometheus-community/pro-bing"
	"net"
	"time"
)

var (
	AddressInvalidErr = errors.New("address is invalid")
)

type PingerConfig struct {
	Count    int
	Interval time.Duration
	Address  string
}

func NewPinger(config *PingerConfig) (*probing.Pinger, error) {
	// 判断config中的address是否是正确的ip地址或者正确的域名
	if !checkAddressValid(config.Address) {
		return nil, AddressInvalidErr
	}

	pinger, err := probing.NewPinger(config.Address)
	if err != nil {
		return nil, err
	}
	if config.Count > 0 {
		pinger.Count = config.Count
	}
	if config.Interval > 0 {
		pinger.Interval = config.Interval
	}
	return pinger, nil
}

func checkAddressValid(address string) bool {
	// 判断address是否是正确的ip地址或者正确的域名
	if address == "" {
		return false
	}
	ip := net.ParseIP(address)
	if ip != nil {
		return true
	}
	_, err := net.LookupHost(address)
	if err != nil {
		return true
	}
	return false
}
